//
//  OAuthViewController.swift
//  Weibo007
//
//  Created by 闫崇 on 15/12/14.
//  Copyright © 2015年 闫崇. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController,UIWebViewDelegate {

    
    //定义常量
    private let WB_Client_ID = "89448046"
    private let WB_Redirect_URI = "http://www.baidu.com"
//    private let WB_Redirect_URIS = "https://www.baidu.com"
    private let WB_Client_Secret = "38c377e9653f0d9960ae23019c602f66"
    // 1.webView 加载授权页面
    var webView : UIWebView?
    override func loadView() {
        //实例化
        webView = UIWebView()
        webView?.delegate = self
        //跟视图就是 webView
        view = webView
        
        //设置 nav 的信息
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        
    }

    
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
 
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = '15076508725' ,document.getElementById('passwd').value = 'yanpengxu199362' "
        
        webView!.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        loadOAuthPage()
        setNavBar()
    }
    
    // MARK:设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }
    
    
    //加载授权界面
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        //! 表示一定能够生成
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
        
    }
    
    
    //MARK - UIWebViewDelegate 方法
    //在代理方法中 如果返回 true 表示一切正常如果返回 false 表示什么也不做
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        /**
        初始
        https://api.weibo.com/oauth2/authorize?client_id=89448046&redirect_uri=http://www.baidu.com
        登录成功
        https://api.weibo.com/oauth2/authorize
        
        授权成功  授权码
        https://m.baidu.com/?code=5baecbad8baa3a17673d52805272c346&from=844b&vit=fps
        
        取消授权
        https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps
        1> 如果是新浪的 URL，就继续加载
        2> 如果是回调地址，需要根据 URL 中的内容，判断是否有授权码
        */
        
//        print(request)
        
        //URL 的完整字符串
        let urlString = request.URL!.absoluteString
        print(urlString)
//        1> 如果不是回调的 URL，就继续加载
        if !urlString.hasPrefix("http://www.baidu.com") {
            //一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
            return true
        }
        
        
        
//        2> 如果是回调地址，需要根据 URL 中的内容，判断是否有授权码

        print("需要判断")
        
        let query = request.URL!.query
        let codeStr = "code="
        
        if query!.hasPrefix(codeStr){
            
            let code = query!.substringFromIndex(codeStr.endIndex)
            print("获取授权码\(code)")
            loadAccessToken(code)
        }else{
            print("取消授权")
            close()
        }
        
        return false
        
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

    
    //使用授权码加载 token
    private func loadAccessToken(code:String){
        
        //urlString
        let urlString = "oauth2/access_token"
        //请求参数
        let params = ["client_id":WB_Client_ID,
                      "client_secret":WB_Client_Secret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WB_Redirect_URI]
        
        
        
        //发起网络请求
        NetworkTool.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            print(JSON)
            
            //字典转模型  ->加载用户信息  链式调用
            userAccount(dict:JSON as! [String : AnyObject]).loadUserInfo({ (account, error) -> () in
                
                //判断账户信息是否正确
                if account != nil {
                    print(account)
                    
                    //1.设置全局的 account
                    sharedUserAccount = account
                    //2.发起通知
                    NSNotificationCenter.defaultCenter().postNotificationName(YCSwitchRootViewController, object: false)
                    //3.关闭当前控制器
                    self.close()
                    
                    return
                }
                
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            })
            //归档保存
//            account.saveAccount()
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
        }
        
    }
    
    
}
